from rest_framework.decorators import action
from rest_framework.permissions import IsAdminUser
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet

from meiduo_admin.serializer.orders import OrderSeriazlier
from meiduo_admin.utils import UserPageNum
from orders.models import OrderInfo


class OrdersView(ModelViewSet):

    # 指定序列化器
    serializer_class = OrderSeriazlier
    # 获取分页器
    pagination_class = UserPageNum
    #权限认证
    permission_classes = [IsAdminUser]


    def get_queryset(self):

        keyword = self.request.query_params.get('keyword')
        if keyword == '' or keyword is None:
            return OrderInfo.objects.all()
        else:
            return OrderInfo.objects.filter(order_id__contains = keyword)

    @action(methods=['put'],detail=True)
    def status(self,request,pk):

        order = self.get_object()
        status = request.data.get('status')
        order.status = status
        order.save()
        ser = self.get_serializer(order)
        return  Response(ser.data)
